<template>
  <PageWrapper title="" contentFullHeight fixedHeight :loading="loading">
    <div class="bg-white h-full p-4">
      <Scrollbar>
        <div class="flex gap-5px items-center justify-center mb-2">
          <div>查询名称</div>
          <div><Input style="width: 150px" v-model:value="dataRef.name" /></div>
          <div><a-button @click="handleSubmit">保存</a-button></div>
          <div><a-button @click="handleDesign">设计器</a-button></div>
          <div><a-button @click="handleSearch" v-if="queryId">查询</a-button></div>
          <div>
            <a-button type="like" @click="handleAddField" v-if="queryId"
              >添加合计字段</a-button
            ></div
          >
        </div>
        <div class="w-full flex flex-wrap gap-2 mb-2">
          <div v-for="(item, index) in statDescList" :key="index" class="flex gap-2 items-center">
            <Select
              :options="dataRef.statOptions"
              v-model:value="item.calcFieldCode"
              style="width: 150px"
              show-search
              optionFilterProp="label"
              :getPopupContainer="(trigger) => trigger?.parentNode"
            />
            <Select
              :options="calcFuncList"
              v-model:value="item.calcFunc"
              style="width: 100px"
              :getPopupContainer="(trigger) => trigger?.parentNode"
            />
            <span class="cursor-pointer" @click="handleDelete(index)">x</span>
          </div>
        </div>
        <div>
          <AceEditor
            v-model:value="dataRef['script']"
            :readonly="true"
            style="height: calc(100vh - 200px)"
          />
        </div>
      </Scrollbar>
    </div>
    <DesignIframe ref="ifrmRef" @register="registerDesignIframeView" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, onUnmounted, onMounted, unref } from 'vue';
  import { Input, Select } from 'ant-design-vue';
  import { PageWrapper } from '/@/components/Page';
  import { Scrollbar } from '/@/components/Scrollbar';
  import { AceEditor } from '/@/components/AceEditor/index';
  import DesignIframe from '/@/views/system/workflow/formManagement/eventDesign/modules/DesignIframe.vue';
  import { useModal } from '/@/components/Modal';
  import { useUserStore } from '/@/store/modules/user';
  import {
    getQueryCreateForScript,
    getQueryEditScriptPage,
    getQueryUpdateForScript,
  } from '/@/api/reportForms/reportForms';
  import { useRouter } from 'vue-router';
  import { isArray } from '/@/utils/is';
  import { useGo } from '/@/hooks/web/usePage';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  const { currentRoute } = useRouter();
  const userStore = useUserStore();
  const queryId = ref('');
  const loading = ref(false);
  const dataRef = ref<Recordable>({});
  function hasDuplicateCode(arr, prop) {
    return arr.some(
      (item, index) =>
        arr.filter((other, otherIndex) => item[prop] === other[prop] && index !== otherIndex)
          .length > 1,
    );
  }
  //保存
  const handleSubmit = async () => {
    try {
      loading.value = true;
      const statDesc = {};
      if (statDescList.value && statDescList.value.length) {
        const hasCode = hasDuplicateCode(statDescList.value, 'calcFieldCode');
        if (hasCode) {
          createMessage.warning('合计字段重复');
          return;
        }
        statDescList.value.forEach((item) => {
          statDesc[item.calcFieldCode] = item.calcFunc;
        });
      }
      const params = {
        op: 'modify',
        queryName: dataRef.value.name,
        isSystem: true,
        script: dataRef.value.script,
        id: '-1',
        statDesc: JSON.stringify(statDesc),
      };
      console.log(params);
      if (!queryId.value) {
        params.op = 'create';
        await getQueryCreateForScript(params);
        createMessage.success('操作成功');
      } else {
        params.id = queryId.value;
        await getQueryUpdateForScript(params);
        createMessage.success('操作成功');
      }
      console.log(params);
    } catch (error) {
    } finally {
      loading.value = false;
    }
  };
  const go = useGo();
  //查询
  const handleSearch = () => {
    go({
      path: '/searchTable',
      query: {
        id: queryId.value,
        title: dataRef.value.name,
        cacheName: `searchTable${queryId.value}`,
      },
    });
  };

  const [registerDesignIframeView, { openModal, closeModal }] = useModal();

  const statDescList = ref<Recordable[]>([]);
  const calcFuncList = [
    {
      value: '0',
      label: '求和',
    },
    {
      value: '1',
      label: '求平均值',
    },
  ];
  //字段合计新增
  const handleAddField = () => {
    statDescList.value.push({
      calcFieldCode: '',
      calcFunc: '0',
    });
  };

  const handleDelete = (index) => {
    statDescList.value.splice(index, 1);
  };

  const fetch = () => {
    statDescList.value = [];
    queryId.value = currentRoute.value.query.id as any;
    if (!queryId.value) {
      return;
    }
    getQueryEditScriptPage({ id: queryId.value }).then((res) => {
      dataRef.value = res;
      if (!isArray(dataRef.value.statOptions)) {
        dataRef.value.statOptions = [];
      }
      if (dataRef.value.statDesc && Object.keys(dataRef.value.statDesc).length > 0) {
        for (let v in dataRef.value.statDesc) {
          statDescList.value.push({
            calcFieldCode: v,
            calcFunc: dataRef.value.statDesc[v],
          });
        }
      }
    });
  };

  onMounted(fetch);

  //设计器
  const handleDesign = () => {
    openModal(true, {
      scriptStr: unref(dataRef).script,
      //   formCode: props.formCode,
    });
  };

  //回调
  const handleSuccess = (value) => {
    console.log('handleSuccess', value);
    if (value) {
      unref(dataRef).script = value;
    }
  };
  const ifrmRef = ref<any>(null);
  let ideUrl = 'script_frame.jsp';
  const onMessage = (e) => {
    var d = e.data;
    var data = d.data;
    var type = d.type;
    if (type == 'setScript') {
      console.log('onMessage data', data);
      dataRef.value.script = data;
      if (d.cwsToken != null) {
        let cwsToken = d.cwsToken;
        ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
      }
      closeModal();
    } else if (type == 'getScript') {
      let serverInfo = userStore.getServerInfo;
      console.log('getScript scriptStr.value=', dataRef.value.script);
      let data = {
        type: 'openerScript',
        version: serverInfo.version,
        spVersion: serverInfo.spVersion,
        // scene: 'flow.' + currentCode.value,
        scene: 'query.script',
        data: dataRef.value.script,
      };
      // window.postMessage(data, '*');
      unref(ifrmRef).doPostMessage(data);
    } else if (type == 'setCwsToken') {
      let cwsToken = d.cwsToken;
      ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
    }
  };

  if (window.addEventListener) {
    // all browsers except IE before version 9
    window.addEventListener('message', onMessage, false);
  }

  onUnmounted(() => {
    console.log('EventDesign-onUnmounted');
    window.removeEventListener('message', onMessage, false);
  });
</script>
<style lang="less" scoped>
  :deep(.ant-tabs-nav) {
    background-color: #fff;
    margin: 0;
  }
</style>
